package dannesNetworkTest;
import java.net.ServerSocket;
import java.net.Socket;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;

import javax.print.attribute.standard.Severity;

public class Server {

	private ServerSocket serverSocket;
	private Socket socket1;
	private Socket socket2;
	private InputStream inputStream1;
	private InputStream inputStream2;
	private ObjectInputStream objIn1;
	private ObjectInputStream objIn2;
	private Boolean running = true;
	
	public static void main(String[] args) {
		Server server = new Server();
	}
	
	public Server() {
		try {
			serverSocket = new ServerSocket(1337);		//Creates a new socket
			socket1 = serverSocket.accept();				//Wait for connection and accept a socket
			socket2 = serverSocket.accept();
			System.out.println("Connection success");
			inputStream1 = socket1.getInputStream();		//Create you inputstream
			inputStream2 = socket2.getInputStream();
			objIn1 = new ObjectInputStream(inputStream1);	//Creates an objectinputstream
			objIn2 = new ObjectInputStream(inputStream2);
			
			new Thread(new Runnable(){									// Create two thread checking from messages from diffrent clients
				String message;
				public void run(){
					try {
						while (running) {
							message = (String) objIn1.readObject();
							System.out.println(message);
							if (message.equals("quit")) {
								running = false;
							}
							Thread.sleep(10);
						}
						objIn1.close();								//Close the stream
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (ClassNotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}).start();
			new Thread(new Runnable(){
				String message;
				public void run(){
					try {
						while (running) {
							message = (String) objIn2.readObject();
							System.out.println(message);
							if (message.equals("quit")) {
								running = false;
							}
							Thread.sleep(10);
						}
						objIn2.close();
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (ClassNotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}).start();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
